import {
  IBillCalendarDaily,
  IBillCategory,
  IBillRecord,
  IBillSummaryStats, IBillType
} from '@/types/bill'
import { formatDate } from 'vue3-common/utils/dateUtil'

/**
 * 获取日程日期
 * @param billRecordList 账单记录
 * @param type 账单类型
 */
export const getCalendarDateList = (billRecordList: IBillRecord[], type: 'expensive' | 'income'): string[] => {
  const resultSet = new Set()
  billRecordList.forEach((item) => {
    if (item.type === type) {
      resultSet.add(formatDate(item.date))
    }
  })

  return [...resultSet] as string[]
}

/**
 * 获取日程日期
 * @param billRecordList 账单记录
 * @param date 日期
 */
export const getCalendarDailyCount = (billRecordList: IBillRecord[],
  date: string): IBillCalendarDaily => {
  const calendarDaily: IBillCalendarDaily = {
    dailyRecordList: [],
    totalExpensive: 0,
    totalIncome: 0
  }

  billRecordList.forEach((value) => {
    // 判断是否是当前日期
    if (formatDate(value.date) === date) {
      calendarDaily.dailyRecordList.push(value)
      // 统计当前日期的收入和支出总和
      if (value.type === 'expensive') {
        calendarDaily.totalExpensive += value.amount
      } else {
        calendarDaily.totalIncome += value.amount
      }
    }
  })

  return calendarDaily
}

/**
 * 计算账单概要统计
 * @param billRecordList 账单记录
 */
export const getBillSummaryStats = (billRecordList: IBillRecord[]): IBillSummaryStats => {
  const billSummaryStats: IBillSummaryStats = {
    balance: 0,
    expensive: 0,
    income: 0,
    rate: 0
  }

  billRecordList.forEach((value) => {
    // 统计当前日期的支出和收入总和
    if (value.type === 'expensive') {
      billSummaryStats.expensive += value.amount
    } else {
      billSummaryStats.income += value.amount
    }
  })

  billSummaryStats.balance = billSummaryStats.income - billSummaryStats.expensive

  // 计算支出/收入
  if (billSummaryStats.expensive === 0) {
    billSummaryStats.rate = 0
  } else if (billSummaryStats.income === 0) {
    billSummaryStats.rate = 1
  } else {
    billSummaryStats.rate = Math.min(billSummaryStats.expensive / billSummaryStats.income, 1)
  }

  return billSummaryStats
}

export const getCategoryByName = (categoryList: IBillCategory[], name: string): IBillCategory => {
  return categoryList.find((item) => item.name === name) || {
    bookName: '',
    name: '',
    type: '',
    icon: ''
  }
}

export const getBillSortByAmount = (billRecordList: IBillRecord[],
  billType: IBillType): IBillRecord[] => {
  return billRecordList.filter((item) => item.type === billType)
    .sort((a, b) => b.amount - a.amount)
}

/**
 * 根据值显示不同的颜色
 */
export const getRateColor = (rate: number) => {
  if (rate <= 0.3) {
    return '#008B8B'
  } else if (rate > 0.3 && rate <= 0.6) {
    return '#FFA500'
  } else {
    return '#CD4F39'
  }
}
